package com.urchin.avatarhero;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.urchin.avatarhero.questview.AvailableQuests;
import com.urchin.avatarhero.questview.CompletedQuests;
import com.urchin.avatarhero.questview.CurrentQuests;
import com.urchin.avatarhero.questview.FailedQuests;
import com.urchin.avatarhero.util.SQLiteHandler;
import com.urchin.avatarhero.util.Utilities;
import com.urchin.avatarhero.util.cal.CalBlob;
import com.urchin.avatarhero.util.cal.CalendarHandler;

/**********************************************************************
AvatarHero - A task management RPG Android Application
Copyright (C) 2013  Peter Clay

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
***********************************************************************/

public class MainActivity extends Activity {
	boolean firstTime;
	Prefs prefs;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Start the UI
        setContentView(R.layout.activity_main);   
        setTitle(R.string.app_name);  
        
        // Restore preferences
        prefs = new Prefs();
        
        // Run the first time setup, if needed
        firstTime = prefs.getMyBoolPref(getApplicationContext(),"first_time");		// Default to true if doesn't exist
        
        if(firstTime) {
        	Toast.makeText(this,"First time Setup!",Toast.LENGTH_LONG).show();
        	Intent intent = new Intent(this, SetupPrefs.class);
        	startActivity(intent);
        } else {
        	refreshMainUI();
        }
    }

    protected void onRestart() {
    	super.onRestart();
    	refreshMainUI();
    }
    
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    protected void onStop() {
    	super.onStop();
    }
    
    /*************************
     * User-Defined Functions
     ************************/
    
    public void refreshMainUI() {
    	// Refresh UI Quick Status
	    TextView textViewName = (TextView) findViewById(R.id.textNameDynamic);
	    textViewName.setText(prefs.getMyStringPref(getApplicationContext(),"char_name"));
	    TextView textViewExp = (TextView) findViewById(R.id.textExpDynamic);
	    textViewExp.setText(Integer.toString(prefs.getMyIntPref(getApplicationContext(),"char_exp")));
	    TextView textViewLvl = (TextView) findViewById(R.id.textLvlDynamic);
	    textViewLvl.setText(Integer.toString(prefs.getMyIntPref(getApplicationContext(),"char_lvl")));
	    
	    // Refresh the Calendar Events
	    CalendarHandler calhandle = new CalendarHandler(this);
	    Utilities util = new Utilities(this);
	    ArrayList<CalBlob> cdata = calhandle.buildCalData(calhandle.getEvents(), calhandle.getInstances());
	   
	    // Build the Upcoming events	    
	    ArrayList<String> elist = new ArrayList<String>();
	    SQLiteHandler dbHandler = new SQLiteHandler(this);
		dbHandler.opendb();
	    for(int i = 0;i < cdata.size();i++) {
	    	if(cdata.get(i).getStarttime() > calhandle.curtime) {		// Event is upcoming and has xp
	    		elist.add(util.convertToStrPattern(cdata.get(i), "caldisp", dbHandler));
	    	}
	    }
	    dbHandler.closedb();
	    
	    for(int i=elist.size();i<calhandle.NUM_TO_DISP;i++) {
	    	elist.add("");
	    }
	    for(int i = 0;i < calhandle.NUM_TO_DISP;i++) {
	    	String buttonid = "buttonTask" + String.valueOf(i+1);
	    	int bid = getResources().getIdentifier(buttonid, "id", getPackageName());
	    	TextView textTaskButton = (TextView) findViewById(bid);
	    	textTaskButton.setText(elist.get(i));
	    }
	    
    }	// End of refreshUI function
    
    public void gotoEvent(View view) {		// Event Button Action
    	CalendarHandler calhandle = new CalendarHandler(this);
    	ArrayList<CalBlob> cdata = calhandle.buildCalData(calhandle.getEvents(), calhandle.getInstances());
    	Button b = (Button) view;
    	String cmptxt = "";
    	Uri uri = null;
    	Intent intent = null;
    	Utilities util = new Utilities(this);
    	SQLiteHandler dbHandler = new SQLiteHandler(this);
		dbHandler.opendb();
    	
    	if(b.getText().toString().trim() != "") {		// Only go if not blank
	    	for(int i=0;i<cdata.size();i++) {		// Find the correct event to start
	    		long ebtime = cdata.get(i).getStarttime();
	    		long eetime = cdata.get(i).getEndtime();
	    		
    			cmptxt = util.convertToStrPattern(cdata.get(i), "caldisp",dbHandler);
	    		
	    		if(b.getText().toString().equals(cmptxt)) {
	    			// Setup for 2.1 support
	    			if(Build.VERSION.SDK_INT <= 7) {							// Old Software
	    				uri = Uri.parse("content://calendar/events/" + String.valueOf(cdata.get(i).getEventid()));
	    				intent = new Intent(Intent.ACTION_VIEW)
	    		    		.setData(uri)
	    					.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
	    					.putExtra("beginTime", ebtime)
	    					.putExtra("endTime", eetime);
	    				startActivity(intent);
	    			} else {
	    				uri = Uri.parse("content://com.android.calendar/events/" + String.valueOf(cdata.get(i).getEventid()));
	    				intent = new Intent(Intent.ACTION_VIEW)
	    		    		.setData(uri)
	    					.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
	    					.putExtra("beginTime", ebtime)
	    					.putExtra("endTime", eetime);
	    				startActivity(intent);
	    			}
	    			break;
	    		}
	    		
	    	}
    	}
    	dbHandler.close();
    }
    
    public void gotoQuests(View view) {
    	// Use the selector to go to the correct quests page
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder
			.setTitle(R.string.quest_select_title)
			.setItems(R.array.quest_select,  new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					if(which == 0) {
						Intent intent = new Intent(getApplicationContext(), AvailableQuests.class);
				    	startActivity(intent);
					} else if(which == 1) {
						Intent intent = new Intent(getApplicationContext(), CurrentQuests.class);
				    	startActivity(intent);
					} else if(which == 2) {
						Intent intent = new Intent(getApplicationContext(), CompletedQuests.class);
				    	startActivity(intent);
					} else if(which == 3) {
						Intent intent = new Intent(getApplicationContext(), FailedQuests.class);
				    	startActivity(intent);
					}
				}
			});
		// Create it and show it
		AlertDialog alert_dialog = builder.create();
		alert_dialog.show();
    }
    
    
    public void runSetup(View view) {		// Setup Button Action
    	Intent intent = new Intent(this, SetupPrefs.class);
    	startActivity(intent);
    }
    
    public void quitMain(View view) {		// Quit Button Action
    	this.finish();
    }
    
    
}
